package com.kudian.restful.service;

import com.kudian.common.exception.ApplicationException;
import com.kudian.common.persistence.HibernateDao;
import com.kudian.common.persistence.ResultObj;
import com.kudian.common.service.BaseService;
import com.kudian.common.utils.DateUtils;
import com.kudian.common.utils.PropertiesLoader;
import com.kudian.common.utils.StringUtils;
import com.kudian.restful.dao.AdDao;
import com.kudian.restful.dao.LayoutDao;
import com.kudian.restful.dao.SmsDao;
import com.kudian.restful.entity.Ad;
import com.kudian.restful.entity.Layout;
import com.kudian.restful.entity.Sms;
import com.kudian.restful.vo.ad.AdItemVO;
import com.kudian.restful.vo.ad.MidAdRetVO;
import com.kudian.restful.vo.ad.MidAdVO;
import com.kudian.restful.vo.sms.SendVeriVO;
import com.kudian.restful.vo.sms.VeriVO;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Administrator on 2016/4/18.
 */
@Service
@Transactional(readOnly = true)
public class SmsService extends BaseService<Sms, Integer> {
    private static final Logger logger = Logger.getLogger(SmsService.class);

    @Autowired
    private SmsDao smsDao;

    @Override
    public HibernateDao<Sms, Integer> getEntityDao() {
        return smsDao;
    }

    @Transactional(readOnly = false)
    public void sendVerificationCd(SendVeriVO vo) throws ApplicationException {
        Sms sms = new Sms();

        PropertiesLoader p = new PropertiesLoader("env.properties");
        String url = p.getProperty("SMS_URL");
        String appkey = p.getProperty("SMS_APP_KEY");
        String secret = p.getProperty("SMS_APP_SECRET");

        Random rnd = new Random();
        int num = rnd.nextInt(89999) + 10000;
        String vericd = num + "";

        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setExtend("");
        req.setSmsType("normal");
        req.setSmsFreeSignName("注册验证");
        req.setSmsParamString("{code:'" + vericd +  "',product:'先客'}");
        req.setRecNum(vo.getMobile());
        req.setSmsTemplateCode( "SMS_12460462" );
        AlibabaAliqinFcSmsNumSendResponse rsp = null;

        try {
            rsp = client.execute(req);

            sms.setMobile(vo.getMobile());
            sms.setVerificationCd(vericd);
            sms.setAddDate(DateUtils.getSysTimestamp());
            smsDao.save(sms);
        } catch (ApiException e) {
            logger.error(e);
            throw new ApplicationException(9999, "发送验证码失败!");
        }
    }

    public boolean checkVerificationCd(VeriVO vo) {
        // 十分钟前
        long ten = DateUtils.getSysTimestamp().getTime() - 10 * 60 * 1000;
        // date.setTime(date.getTime() + 15*60*1000);

        List<Sms> smses = this.smsDao.findbyorder("addDate", false,
                Restrictions.eq("mobile", vo.getMobile()), Restrictions.eq("verificationCd", vo.getVerificationCd()),
                Restrictions.ge("addDate", new Date(ten)));

        if (smses != null && !smses.isEmpty()) {
            return true;
        }
        return false;
    }
}
